package cn.hx.admin.service.impl;

import cn.hx.admin.dao.ScheduleTaskDao;
import cn.hx.admin.entity.JobLog;
import cn.hx.admin.entity.ScheduleTask;
import cn.hx.admin.schedule.MyJob;
import cn.hx.admin.service.JobLogService;
import cn.hx.admin.service.ScheduleTaskService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import static cn.hx.admin.util.ScheduleConstant.*;

/**
 * 定时任务(ScheduleTask)表服务实现类
 *
 * @author makejava
 * @since 2023-12-07 11:32:58
 */
@Service("scheduleTaskService")
public class ScheduleTaskServiceImpl implements ScheduleTaskService {
    @Resource
    private ScheduleTaskDao scheduleTaskDao;

    @Resource
    private JobLogService jobLogService;


    private static Scheduler scheduler;

    static {
        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过ID查询单条数据
     *
     * @param jobId 主键
     * @return 实例对象
     */
    @Override
    public ScheduleTask queryById(Long jobId) {
        return this.scheduleTaskDao.queryById(jobId);
    }


    /**
     * 分页查询
     *
     * @param scheduleTask 筛选条件
     * @return 查询结果
     */
    @Override
    public List<ScheduleTask> queryByPage(ScheduleTask scheduleTask) {
        return this.scheduleTaskDao.queryAll(scheduleTask);
    }

    /**
     * 新增数据
     *
     * @param scheduleTask 实例对象
     * @return 实例对象
     */
    @Override
    public ScheduleTask insert(ScheduleTask scheduleTask) {
        this.scheduleTaskDao.insert(scheduleTask);
        return scheduleTask;
    }

    /**
     * 修改数据
     *
     * @param scheduleTask 实例对象
     * @return 实例对象
     */
    @Override
    public ScheduleTask update(ScheduleTask scheduleTask) {
        this.scheduleTaskDao.update(scheduleTask);
        return this.queryById(scheduleTask.getJobId());
    }

    /**
     * 通过主键删除数据
     *
     * @param jobId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long jobId) {
        return this.scheduleTaskDao.deleteById(jobId) > 0;
    }

    @Override
    public ScheduleTask changeStatus(Long id, String status) {
        ScheduleTask scheduleTask = scheduleTaskDao.queryById(id);
        scheduleTask.setStatus(Integer.valueOf(status));
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        // 格式化日期
        String formattedDate = today.format(formatter);
        try {
            scheduleTaskDao.update(scheduleTask);
            if (SCHEDULE_STATUS.equals(status)) {
                JobLog jobLog = new JobLog();
                jobLog.setJobName(scheduleTask.getBeanName());
                jobLog.setJobGroup(scheduleTask.getMethodName());
                jobLog.setInvokeTarget(scheduleTask.getCronExpression());
                jobLog.setStatus(String.valueOf(scheduleTask.getStatus()));
                jobLog.setExceptionInfo("成功执行！");
                jobLog.setJobMessage("定时任务启动成功！");
                jobLog.setCreateTime(new Date());
                jobLogService.insert(jobLog);
                if (SCHEDULE_JOB2.equals(scheduleTask.getJobId())) {
                    // 创建JobDetail
                    JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                            .withIdentity(scheduleTask.getBeanName(), scheduleTask.getMethodName())
                            .build();
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put("scheduleTask", scheduleTask);
                    jobDataMap.put("start", formattedDate + " 08:30:00");
                    jobDataMap.put("end", formattedDate + " 09:00:00");
                    jobDetail.getJobDataMap().putAll(jobDataMap);
                    // 创建触发器
                    Trigger trigger = TriggerBuilder.newTrigger()
                            .withIdentity(scheduleTask.getBeanName() + "Trigger", scheduleTask.getMethodName())
                            .withSchedule(CronScheduleBuilder.cronSchedule(scheduleTask.getCronExpression()))
                            .build();
                    scheduler.scheduleJob(jobDetail, trigger);
                    // 开启调度器
                    scheduler.start();
                } else if (SCHEDULE_JOB3.equals(scheduleTask.getJobId())) {
                    // 创建JobDetail
                    JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                            .withIdentity(scheduleTask.getBeanName(), scheduleTask.getMethodName())
                            .build();
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put("scheduleTask", scheduleTask);
                    jobDataMap.put("start", formattedDate + " 08:00:00");
                    jobDataMap.put("end", formattedDate + " 17:00:00");
                    jobDetail.getJobDataMap().putAll(jobDataMap);

                    // 创建触发器
                    Trigger trigger = TriggerBuilder.newTrigger()
                            .withIdentity(scheduleTask.getBeanName() + "Trigger", scheduleTask.getMethodName())
                            .withSchedule(CronScheduleBuilder.cronSchedule(scheduleTask.getCronExpression()))
                            .build();
                    scheduler.scheduleJob(jobDetail, trigger);
                    // 开启调度器
                    scheduler.start();
                } else {
                    // 创建JobDetail
                    JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                            .withIdentity(scheduleTask.getBeanName(), scheduleTask.getMethodName())
                            .build();
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put("scheduleTask", scheduleTask);
                    jobDataMap.put("start", formattedDate + " 05:00:00");
                    jobDataMap.put("end", formattedDate + " 05:30:00");
                    jobDetail.getJobDataMap().putAll(jobDataMap);
                    // 创建触发器
                    Trigger trigger = TriggerBuilder.newTrigger()
                            .withIdentity(scheduleTask.getBeanName() + "Trigger", scheduleTask.getMethodName())
                            .withSchedule(CronScheduleBuilder.cronSchedule(scheduleTask.getCronExpression()))
                            .build();
                    scheduler.scheduleJob(jobDetail, trigger);
                    // 开启调度器
                    scheduler.start();
                }
            } else {
                JobKey jobKey = new JobKey(scheduleTask.getBeanName(), scheduleTask.getMethodName());
                scheduler.deleteJob(jobKey);
                JobLog jobLog = new JobLog();
                jobLog.setJobName(scheduleTask.getBeanName());
                jobLog.setJobGroup(scheduleTask.getMethodName());
                jobLog.setInvokeTarget(scheduleTask.getCronExpression());
                jobLog.setStatus(String.valueOf(scheduleTask.getStatus()));
                jobLog.setExceptionInfo("成功执行！");
                jobLog.setJobMessage("定时任务取消！");
                jobLog.setCreateTime(new Date());
                jobLogService.insert(jobLog);
            }

        } catch (Exception e) {
            JobLog jobLog = new JobLog();
            jobLog.setJobName(scheduleTask.getBeanName());
            jobLog.setJobGroup(scheduleTask.getMethodName());
            jobLog.setInvokeTarget(scheduleTask.getCronExpression());
            jobLog.setStatus(String.valueOf(scheduleTask.getStatus()));
            jobLog.setExceptionInfo(e.getMessage());
            jobLog.setJobMessage("定时任务执行异常！");
            jobLog.setCreateTime(new Date());
            jobLogService.insert(jobLog);
            return null;
        }
        return scheduleTask;
    }
}
